//
//  ZDBRegisterViewController.m
//  ZDB
//
//  Created by 微笑吧阳光 on 2020/3/22.
//  Copyright © 2020 ZDB. All rights reserved.
//

#import "ZDBRegisterViewController.h"
#import "DJLoginEnterTextItemCell.h"
#import "TPKeyboardAvoidingTableView.h"
#import "DJLoginFooterActionView.h"
#import "UIButton+CountDown.h"
#import "ZDBInformationViewController.h"
#import "ZDBKeychainTool.h"

@interface ZDBRegisterViewController ()
<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)TPKeyboardAvoidingTableView * ks_TableView2;
@property(nonatomic,strong) NSMutableArray * modelsArry2;
@property(nonatomic,strong) DJLoginFooterActionView * footerView;
@property(nonatomic,strong) NSData * imageData;
@end

@implementation ZDBRegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self creatUI];
    
    [self request_ImageCode];
    
    
}


-(void)creatUI{
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.ks_TableView2];
   [_ks_TableView2 registerNib:[UINib nibWithNibName:@"DJLoginEnterTextItemCell" bundle:nil]  forCellReuseIdentifier:@"DJLoginEnterTextItemCell"];
    
    UIView * headerV = [BBControl createViewWithFrame:CGRectMake(0, 0, kScreenWidth, 200)];
    headerV.backgroundColor = [UIColor clearColor];
    
    UIImageView * heaserImage = [BBControl createImageViewFrame:CGRectMake(50, 0, kScreenWidth-100, 200) imageName:@"logo-big" ];
    heaserImage.contentMode = UIViewContentModeCenter;
    [headerV addSubview:heaserImage];
    _ks_TableView2.tableHeaderView = headerV;
    
    self.footerView = [[NSBundle mainBundle]loadNibNamed:@"DJLoginFooterActionView" owner:self options:nil].lastObject;
    self.footerView .frame =CGRectMake(0, 0, kScreenWidth, 250);
    self.footerView.fogetBtn.hidden = YES;
    [self.footerView.loginBtn setTitle:@"注 册" forState:0];
     _ks_TableView2.tableFooterView = self.footerView;
    self.footerView.tishiLab.hidden = NO;
    self.footerView.loginbtnTopC.constant = 0;
    self.footerView.goBackBtn.hidden = NO;
    
    WEAKSELF
    [self.footerView.goBackBtn add_BtnClickHandler:^(NSInteger tag) {
        STRONGSELFFor(weakSelf);
        [strongSelf.navigationController popViewControllerAnimated:YES];
    }];

    [self.footerView.loginBtn add_BtnClickHandler:^(NSInteger tag) {
        STRONGSELFFor(weakSelf);
        [strongSelf userRequestAction];
    }];
}



-(void)request_ImageCode{
    //commen_getImageCode
    WEAKSELF
    NSString  * url = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"commen_getImageCode"];
    [[SmileHttpTool sharedInstance] GET_Data:url parameters:nil origin:YES success:^(NSInteger statusCode, NSURLSessionDataTask *task, id responseObject) {
        STRONGSELFFor(weakSelf);
         NSLog(@"commen_getImageCode----%@",responseObject);
        NSData * imageData = [NSData dataWithData:responseObject];
        strongSelf.imageData = imageData;
        [strongSelf.ks_TableView2 reloadData];

    } failure:^(id responseObject, NSError *error) {
      
    }];

    //[self infoHeaderImageAndNameMoreEdit];
}

-(void)infoHeaderImageAndNameMoreEdit{
    
    ZDBInformationViewController * vcc = [ZDBInformationViewController new];
    vcc.title = @"完善资料";
    [self.navigationController pushViewController:vcc animated:YES];
    
}

#pragma  mark -----tableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    return 5;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 70;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    DJLoginEnterTextItemCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DJLoginEnterTextItemCell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [self stupCell:cell atIndex:indexPath];
    return cell;
    
}

-(void)stupCell:(DJLoginEnterTextItemCell *)cell  atIndex:(NSIndexPath *)indexPath{
    cell.textTF.tag = indexPath.row;
     [cell.textTF addTarget:self action:@selector(changedTextField:) forControlEvents:UIControlEventEditingChanged];
       
    switch (indexPath.row) {
        case 0:
        {
           // cell.textTF.text = @"musatest3";
            cell.textTF.keyboardType = UIKeyboardTypeNumberPad;
            cell.textTF.placeholder = @"请输入手机号";
            cell.iconImage.image = [UIImage imageNamed:@"login_user-1"];
           // [RestrictionInput restrictionInputTextField:cell.textTF maxNumber:10 showView:self.view showErrorMessage:@"用户名长度必须在6~10个字符"];
              cell.textTF.secureTextEntry = NO;
            NSMutableAttributedString *placeholderString = [[NSMutableAttributedString alloc] initWithString:@"请输入手机号" attributes:@{NSForegroundColorAttributeName : [UIColor colorWithHexString:@"#adadad"]}];
            cell.textTF .attributedPlaceholder = placeholderString;

        }
            break;
            case 1:
            {
               cell.textTF.keyboardType = UIKeyboardTypeDefault;
                cell.textTF.placeholder = @"请输入图形验证码";
                cell.codeImage.hidden = NO;
                cell.anginBtn.hidden = NO;
                NSMutableAttributedString *placeholderString = [[NSMutableAttributedString alloc] initWithString:@"请输入图形验证码" attributes:@{NSForegroundColorAttributeName :  [UIColor colorWithHexString:@"#adadad"]}];
                cell.textTF .attributedPlaceholder = placeholderString;
                cell.iconImage.image = [UIImage imageNamed:@"txyzm"];
                if (self.imageData) {
                    cell.codeImage.image = [UIImage imageWithData:self.imageData];
                }
                WEAKSELF
                [cell.anginBtn add_BtnClickHandler:^(NSInteger tag) {
                    STRONGSELFFor(weakSelf);
                    [strongSelf request_ImageCode];
                }];
                
                
                
            }
                break;
            case 2:
               {
             cell.textTF.keyboardType = UIKeyboardTypeNumberPad;
                  cell.textTF.placeholder = @"请输入手机验证码";
                   cell.codeBtn.hidden = NO;
                   NSMutableAttributedString *placeholderString = [[NSMutableAttributedString alloc] initWithString:@"请输入手机验证码" attributes:@{NSForegroundColorAttributeName :  [UIColor colorWithHexString:@"#adadad"]}];
                   cell.textTF .attributedPlaceholder = placeholderString;
                   cell.iconImage.image = [UIImage imageNamed:@"login_yzm"];
                     WEAKSELF
                   [cell.codeBtn add_BtnClickHandler:^(NSInteger tag) {
                                STRONGSELFFor(weakSelf);
                       [strongSelf phoneCode_ActionRequest:cell.codeBtn];
                            }];
                            
               }
                   break;
        case 3:
        {
             cell.textTF.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
            NSDictionary * user_loginInfo = [kUserDefaults objectForKey:@"user_loginInfo"];
            if (!kDictIsEmpty(user_loginInfo)) {
                         cell.textTF.text = [user_loginInfo jsonString:@"password"];
                     }
             cell.textTF.placeholder = @"请输入密码（6-12位数字字母组合）";
             cell.textTF.secureTextEntry = YES;
            NSMutableAttributedString *placeholderString = [[NSMutableAttributedString alloc] initWithString:@"请输入密码（6-12位数字字母组合）" attributes:@{NSForegroundColorAttributeName :  [UIColor colorWithHexString:@"#adadad"]}];
            cell.textTF .attributedPlaceholder = placeholderString;
            cell.iconImage.image = [UIImage imageNamed:@"login_icon_10"];
        }
            break;
            case 4:
            {
                 cell.textTF.keyboardType = UIKeyboardTypeNumberPad;
                 cell.textTF.placeholder = @"请输入邀请码";
                 cell.textTF.secureTextEntry = YES;
                NSMutableAttributedString *placeholderString = [[NSMutableAttributedString alloc] initWithString:@"请输入邀请码" attributes:@{NSForegroundColorAttributeName :  [UIColor colorWithHexString:@"#adadad"]}];
                cell.textTF .attributedPlaceholder = placeholderString;
                cell.iconImage.image = [UIImage imageNamed:@"yaoqing"];
            }
                break;
            
        default:
            break;
    }

}


-(void)changedTextField:(UITextField *)textField
{
    switch (textField.tag) {
        case 0:
        {
               [RestrictionInput restrictionInputTextField:textField maxNumber:11 showView:self.view showErrorMessage:@"0~12字符~"];
        }
            break;
            case 1:
                  {
                      [RestrictionInput restrictionInputTextField:textField maxNumber:6 showView:self.view showErrorMessage:@"0~12字符~"];
                  }
                      break;
            case 2:
                  {
                       [RestrictionInput restrictionInputTextField:textField maxNumber:6 showView:self.view showErrorMessage:@"0~12字符~"];
                  }
                      break;
            case 3:
                  {
                      [RestrictionInput restrictionInputTextField:textField maxNumber:12 showView:self.view showErrorMessage:@"0~12字符~"];
                  }
                      break;
            case 4:
                         {
                             [RestrictionInput restrictionInputTextField:textField maxNumber:15 showView:self.view showErrorMessage:@"0~12字符~"];
                         }
                             break;
            
        default:
            break;
    }
 
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //[self dismissViewControllerAnimated:YES completion:nil];

}

-(void)phoneCode_ActionRequest:(UIButton *)sender{
    
    DJLoginEnterTextItemCell * phoneCell = [self.ks_TableView2 cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    DJLoginEnterTextItemCell * imageCell = [self.ks_TableView2 cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
    
    if (kStringIsEmpty(phoneCell.textTF.text)) {
        [JMNotifyView showNotify:@"请输入正确的手机号" isSuccessful:NO];
        return;
    }
    if ([self  isMobileNumChack:phoneCell.textTF.text]==NO) {
        [JMNotifyView showNotify:@"请输入正确格式的手机号~" isSuccessful:NO];
         return;
        
    }
    
    if (kStringIsEmpty(imageCell.textTF.text)) {
             [JMNotifyView showNotify:@"请输入图形验证码" isSuccessful:NO];
             return;
    }

    NSString  * url = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"UserCode_SendMsgMobileAction"];
    NSMutableDictionary  *dicc = [NSMutableDictionary dictionary];
    [dicc setValue:phoneCell.textTF.text forKey:@"tel"];
    [dicc setValue:imageCell.textTF.text forKey:@"imageCode"];
    
  //  WEAKSELF
    [[SmileHttpTool sharedInstance] POST:url parameters:dicc origin:NO success:^(NSInteger statusCode, NSString *message, id responseObject) {
        if (statusCode ==0) {
                  dispatch_async(dispatch_get_main_queue(), ^{
                       [sender scheduledTimerWithTimeInterval:60.0f title:@"重新获取" countDownTitle:@"s" titleBackgroundColor:MAINCOLOR countDownTitleBackgroundColor:[UIColor lightGrayColor]];
                            [JMNotifyView showNotify:@"手机验证码已发送,注意查收" isSuccessful:YES];

                        });
        }else{
             [JMNotifyView showNotify:message isSuccessful:NO];
        }
    } failure:^(id responseObject, NSError *error) {
        [JMNotifyView showNotify:@"网络错误，请重试~" isSuccessful:NO];
    }];
    
    
}
-(void)userRequestAction{
    [self.view endEditing:YES];
       DJLoginEnterTextItemCell *cell = [self.ks_TableView2 cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
        DJLoginEnterTextItemCell *cell1 = [self.ks_TableView2 cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
        DJLoginEnterTextItemCell *cell2 = [self.ks_TableView2 cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]];
        DJLoginEnterTextItemCell *cell3 = [self.ks_TableView2 cellForRowAtIndexPath:[NSIndexPath indexPathForRow:3 inSection:0]];
        DJLoginEnterTextItemCell *cell4 = [self.ks_TableView2 cellForRowAtIndexPath:[NSIndexPath indexPathForRow:4 inSection:0]];
    if (kStringIsEmpty(cell.textTF.text)) {
           [JMNotifyView showNotify:@"请输入手机号" isSuccessful:NO];
           return;
       }
    if (kStringIsEmpty(cell2.textTF.text)) {
           [JMNotifyView showNotify:@"请输入手机验证码" isSuccessful:NO];
           return;
       }
    
    if (kStringIsEmpty(cell3.textTF.text)) {
          [JMNotifyView showNotify:@"请输入密码" isSuccessful:NO];
          return;
      }
    if (cell3.textTF.text.length <6 ) {
        [JMNotifyView showNotify:@"密码不能少于6位字符" isSuccessful:NO];
        return;
    }
    
    if ([self isBlank:cell3.textTF.text]==YES || [cell3.textTF.text containsString:@"."]) {
            [JMNotifyView showNotify:@"密码不能包含空格和小数点" isSuccessful:NO];
        return;
    }
    
    if ([self judgePassWordLegal:cell3.textTF.text] ==NO ) {
        [JMNotifyView showNotify:@"密码长度为6~12个字符，不能含有空格或小数点，不能是9位以下纯数字" isSuccessful:NO];
        return;
    }
    
    
       NSString  * url =[[YINetWorkAPIGenerate sharedInstance] APINomark:@"user_LoginuserRegister"];
       [self showLoadingAnimation];
        NSMutableDictionary  *dicc = [NSMutableDictionary dictionary];
        [dicc setValue:cell1.textTF.text forKey:@"imageCode"];
        [dicc setValue:cell3.textTF.text forKey:@"passWord"];
        [dicc setValue:cell2.textTF.text forKey:@"telCode"];
        [dicc setValue:cell.textTF.text forKey:@"userName"];
        [dicc setValue:[NSString stringWithFormat:@"IOS-%@",[ZDBKeychainTool getDeviceIDInKeychain]] forKey:@"mac"];
    if (kStringIsEmpty(cell4.textTF.text)) {
             //   [dicc setValue:@"" forKey:@"userCode"];
        }else{
                [dicc setValue:cell4.textTF.text forKey:@"userCode"];
        }
        WEAKSELF
        [[SmileHttpTool sharedInstance] POST :url parameters:dicc origin:NO success:^(NSInteger statusCode, NSString *message, id responseObject) {
             [self stopLoadingAnimation];
            STRONGSELFFor(weakSelf)
           
            if (statusCode ==0) {
                [JMNotifyView showNotify:@"注册成功" isSuccessful:YES];
                NSDictionary * dataDicc = [NSDictionary dictionaryWithDictionary:responseObject];
                  NSLog(@"user_LoginuserRegister-----%@",dataDicc);
                  NSString *  token = [dataDicc jsonString:@"token"];
                [kUserDefaults setValue:[dataDicc jsonDict:@"userinfo"] forKey:@"user_loginInfo"];
                  [[DJLoginHelper sharedInstance]save_Token:token];
                [[DJLoginHelper sharedInstance]save_UserInfo:[dataDicc jsonDict:@"userinfo"]];
               [[NSNotificationCenter defaultCenter] postNotificationName:LoginSusessNotificationse object:nil];
                [strongSelf infoHeaderImageAndNameMoreEdit];
//                [strongSelf dismissViewControllerAnimated:YES completion:nil];
               // [strongSelf userLoginRequestWith:cell.textTF.text password:cell3.textTF.text];
            }else{
               [JMNotifyView showNotify:message isSuccessful:NO];
            }

        } failure:^(id responseObject, NSError *error) {
            NSLog(@"error----%@",error);
            [JMNotifyView showNotify:@"网络错误，请重试~" isSuccessful:NO];
             [self stopLoadingAnimation];
        }];
    
    
}




- (BOOL)judgePassWordLegal:(NSString *)pass{
    BOOL result = false;
    if ([pass length] >= PassworldLastlength){
        // 判断长度大于6位后再接着判断是否同时包含数字和字符
        //@"^(?=.*[0-9])(?=.*[a-zA-Z])(.{6,16})$";
        NSString * regex = @"^(?=.*[a-zA-Z])(.{6,12})$";
        NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
        result = [pred evaluateWithObject:pass];
        if (result ==NO) {
            return NO;
        }
    }
    NSRange range = [pass rangeOfString:@" "];
    if (range.location != NSNotFound) {
        return NO; //yes代表包含空格
    }else {
        
        NSRange range = [pass rangeOfString:@"."];
        if (range.location != NSNotFound) {
            return NO; //yes
        }else {
            
            return YES; //反之
        }
    }
    return result;
    
}
/**
 * 判断字符串是否包含空格
 */
-(BOOL)isBlank:(NSString *)str{
    NSRange _range = [str rangeOfString:@" "];
    if (_range.location != NSNotFound) {
        //有空格
       // NSLog(@"有空格");
        return YES;
    }else {
        //没有空格
       // NSLog(@"没有空格");
        return NO;
    }
}
/**
 * 判断字符串是否包含空格
 */
-(BOOL)isXiaoShuDian:(NSString *)str{
    NSRange _range = [str rangeOfString:@"."];
    if (_range.location != NSNotFound) {
        //有空格
       // NSLog(@"有小数点");
        return YES;
    }else {
        //没有空格
       // NSLog(@"没有小数点");
        return NO;
    }
}
/**
 * 判断输入的是否是中文
 */
-(BOOL)IsChinese:(NSString *)str

{
    
    NSInteger count = str.length;
    
    NSInteger result = 0;
    
    for(int i=0; i< [str length];i++)
        
    {
        
        int a = [str characterAtIndex:i];
        
        if( a > 0x4e00 && a < 0x9fff)//判断输入的是否是中文
            
        {
            
            result++;
            
        }
        
    }
    
    if (count == result) {//当字符长度和中文字符长度相等的时候
        
        return YES;
        
    }
    
    return NO;
    
}
-(BOOL)isMobileNumChack:(NSString *)input{
    
    input = [input stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (input.length != 11) {
        return NO;
    } else {
        
        //^((13[0-9])|(14[1]|[4-9])|(15([0-3]|[5-9]))|(16[2]|[5-7])|(17[0-3]|[5-8])|(18[0-9])|(19[1|8|9]))\\d{8}$
        
        NSString * CT = @"^1[3|4|5|6|7|8|9][0-9]{9}$";
        NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
        BOOL res4 = [regextestct evaluateWithObject:input];
        if (res4 ) {
            return YES;
        }else {
            return NO;
        }
    }
    
}

#pragma mark ------setter   ---getter
-(TPKeyboardAvoidingTableView*)ks_TableView2
{
    if (_ks_TableView2==nil) {
        _ks_TableView2=[[TPKeyboardAvoidingTableView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) style:UITableViewStylePlain];
        _ks_TableView2.separatorColor=[UIColor clearColor];
        _ks_TableView2.delegate=self;
        _ks_TableView2.backgroundColor = [UIColor clearColor];
        _ks_TableView2.dataSource=self;
        _ks_TableView2.sectionFooterHeight=0.01;
        _ks_TableView2.separatorStyle = UITableViewCellSeparatorStyleNone;
        if (@available(iOS 11.0, *)) {
            _ks_TableView2.estimatedRowHeight =0;
            _ks_TableView2.estimatedSectionHeaderHeight =0;
            _ks_TableView2.estimatedSectionFooterHeight =0;
            _ks_TableView2.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        
    }
    return _ks_TableView2;
}

//2020-03-24 10:47:47.005972+0800 ZDB[3153:99562] responseObject---{
//    data =     {
//        token = "eyJudW1iZXIiOiIxNTg1MDE4MDY2OTM1In0=.eyJpc3MiOiJ6ZGIiLCJleHAiOiIwIiwiaWF0IjoiMTU4NTAxODA2NjkzNSIsImV4cERhdGEiOnsiaWQiOjMsInVzZXJOYW1lIjoiMTMxNzUxMTAwNTEifX0=.uUQHGnu+DKdERQE9Umvq2KVPEx9/0u+sgGiPciKN2my004vhslPGyb2c73LfqCCyenaG8XVH8X2I4hB0A2O2GQ==";
//        userinfo =         {
//            createTime = "<null>";
//            headImage = "";
//            id = 3;
//            integral = 0;
//            money = 0;
//            nikeName = "";
//            offset = 0;
//            pageNum = 0;
//            pageSize = 0;
//            passWord = "";
//            signCount = 0;
//            signIntegral = 0;
//            sumIntegral = 0;
//            uid = 0;
//            userCode = 1585018066794;
//            userName = 13175110051;
//            wxNikeName = "";
//            wxNumber = "";
//            wxOpenid = "";
//            zfbImage = "";
//            zfbName = "";
//            zfbNumber = "";
//        };
//    };
//    message = "\U8bf7\U6c42\U6210\U529f";
//    statusCode = 0;
//}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
